<template>
    <div class="about">
        <h1>{{id?'编辑':'新建'}}文章</h1>
        <el-form label-width="120px" @submit.native.prevent="save">
            <el-form-item label="所属分类">
                <el-select v-model="model.categories" multiple>
                    <el-option v-for="item in categories" :key="item._id" :label="item.name" :value="item._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="标题">
                <el-input v-model="model.title"></el-input>
            </el-form-item>
            <el-form-item label="详情">
                <vue-editor v-model="model.body" 
                useCustomImageHandler 
                @image-added="handleImageAdded">
                </vue-editor>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" native-type="submit">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {VueEditor} from 'vue2-editor'
export default {
    props:{
        id:{}
    },
    components:{
        VueEditor
    },
    data(){
        return{
            model:{},
            categories:[],
        }
    },
    methods: {
        //vue2-editor中解决图片直接添加到页面上去的问题 自定义上传图片上传器
        async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
            const formData = new FormData();
            formData.append("file", file);
            const res=await this.$http.post('upload',formData)

            Editor.insertEmbed(cursorLocation, "image",res.data.url);
            resetUploader();
        },
        async save(){
            //有ID则用put，没有ID则用post
            if(this.id){
                await this.$http.put(`rest/articles/${this.id}`,this.model)
            }else{
                await this.$http.post('rest/articles',this.model)
            }
            this.$router.push('/articles/list')
            //这个是element提供的方法
            this.$message({
                type:'success',
                message:'保存成功'
            })
        },
        //用来显示当编辑数据时input框里的初始内容
        async fetch(){
            //params会出现在请求头中的querry string parameters中，并且会出现在浏览器的地址栏中，即会拼接到url中。
            const res=await this.$http.get(`rest/articles/${this.id}`)
            this.model=res.data
        },
        async fetchCategroies(){
            const res=await this.$http.get(`rest/categories`)
            //这里获取的还只是父级的数据并不是选项
            this.categories=res.data
        }
    },
    created(){
        this.fetchCategroies()
        this.id && this.fetch()
    }
}
</script>